package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.Result;

import com.itheima.dto.OrderDto;
import com.itheima.pojo.AddressBook;
import com.itheima.pojo.OrderDetail;
import com.itheima.pojo.Orders;
import com.itheima.pojo.User;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;

import com.itheima.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrdersController {


    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    //    Request URL: http://localhost:8080/order/submit
//    Request Method: POST
    @PostMapping("/submit")
    public Result submitOrders(@RequestBody Orders orders) {

        ordersService.submitOrders(orders);
        return Result.success("下单成功");
    }

//    Request URL: http://localhost:8080/order/userPage?page=1&pageSize=5
//    Request Method: GET
//Request URL: http://localhost:8080/order/userPage?page=1&pageSize=10&number=17
//    Request Method: GET
    @GetMapping("/userPage")
    public Result userPage(int page, int pageSize,Long number,String beginTime,String endTime) {

        IPage<Orders> pages = new Page<>(page, pageSize);

        List<Orders> orderDtos = new ArrayList<>();

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getOrderTime)
                .between( StringUtils.hasLength(beginTime)&& StringUtils.hasLength(endTime),Orders::getOrderTime,beginTime,endTime)
                .like(number!=null,Orders::getNumber,number);

        ordersService.page(pages, lqw);

        for (Orders record : pages.getRecords()) {

            Long recordId = record.getId();

            LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
            qw.eq(OrderDetail::getOrderId, recordId);
            List<OrderDetail> list = orderDetailService.list(qw);

            Long userId = record.getUserId();
            User user = userService.getById(userId);
            String username = user.getName();


            OrderDto orderDto = new OrderDto();

            BeanUtils.copyProperties(record, orderDto);

            orderDto.setOrderDetails(list);
            orderDto.setUserName(username);

            orderDtos.add(orderDto);

        }

        pages.setRecords(orderDtos);

        return Result.success(pages);
    }


}
